/**
 * 聊天列表页面脚本
 */

// ==================== 获取 IPC 通信 ====================
const { ipcRenderer } = require('electron');

// ==================== 系统通知聊天项 ====================
const SYSTEM_NOTIFICATION_ID = 'system-notifications';

// ==================== 模拟数据 ====================
const mockChats = [
  // 🔔 系统通知（置顶）
  {
    id: SYSTEM_NOTIFICATION_ID,
    name: '系统通知',
    avatar: '../assets/334P.svg',
    lastMessage: '点击查看系统通知消息',
    time: '刚刚',
    unread: 0,
    online: true,
    pinned: true,
    isSystemNotification: true
  },
  {
    id: 1,
    name: '男装商家群',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group1',
    lastMessage: '【全托管】本季度已收到客户十多万好评...',
    time: '15:36',
    unread: 3,
    online: true,
    pinned: false
  },
  {
    id: 2,
    name: '同传云翻译新计划交流群',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group2',
    lastMessage: '王小明: 你好呀，我认为这个翻译一直很棒...',
    time: '12:36',
    unread: 0,
    online: true,
    pinned: false
  },
  {
    id: 3,
    name: '【全托管赋能】雪雾日志直播学习方案',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group3',
    lastMessage: '欢迎光临【我超了！全球全托管活动免费分享...',
    time: '12:36',
    unread: 0,
    online: false,
    pinned: false
  },
  {
    id: 4,
    name: '【外卖】全托管新卖家突破性传播优惠券',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group4',
    lastMessage: '现场课: 都来看，让我认识一位真诚的朋友...',
    time: '14:32',
    unread: 0,
    online: true,
    pinned: false
  },
  {
    id: 5,
    name: 'IT全托管+全站经营知识体系分享课程',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group5',
    lastMessage: 'MoonlightBob1 YT300382743682,白菲等9位新朋...',
    time: '12:00',
    unread: 0,
    online: false,
    pinned: false
  },
  {
    id: 6,
    name: '【全托管官网】雪雾日志直通生产工人真人！',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group6',
    lastMessage: '欢迎您 听听正哥分享亲身经历',
    time: '11:18',
    unread: 0,
    online: true,
    pinned: false
  },
  {
    id: 7,
    name: '青山生态朋友圈开播有限公司官方直播间',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group7',
    lastMessage: '【福建 Siz】跳跃动效+【小课堂】通用站点...',
    time: '10:16',
    unread: 0,
    online: false,
    pinned: false
  },
  {
    id: 8,
    name: 'Shawn\'s店铺工会讨论群',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group8',
    lastMessage: '草草 主体 能说了会 您一天涯时间',
    time: '昨天',
    unread: 0,
    online: true,
    pinned: false
  },
  {
    id: 9,
    name: 'IT全托管+全站经营知识体系分享课程',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group9',
    lastMessage: '李想课: 11月付费课程，10月这全盘店铺营...',
    time: '昨天',
    unread: 0,
    online: false,
    pinned: false
  },
  {
    id: 10,
    name: '【禁麦】雪雾直播(Vr店）',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group10',
    lastMessage: '医生: 剑锋然，天工，头下午会李明宝传数师...',
    time: '昨天',
    unread: 0,
    online: true,
    pinned: false
  },
  {
    id: 11,
    name: '【亚太】蓝宗电信运营年复兴运营术',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group11',
    lastMessage: '张帐: 财经系，天工于下不小宝合明可可明...',
    time: '昨天',
    unread: 0,
    online: false,
    pinned: false
  },
  {
    id: 12,
    name: '全托毛具投资收获AI实测精打细算',
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=group12',
    lastMessage: '李说课: 我是一个小农家，小天下会劳财更...',
    time: '10月18日',
    unread: 0,
    online: true,
    pinned: false
  }
];

const mockMessages = {
  1: [
    {
      id: 1,
      type: 'received',
      content: '大家好，欢迎加入男装商家群！',
      time: '10:00',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user1',
      sender: '管理员'
    },
    {
      id: 2,
      type: 'received',
      content: '【全托管】本季度已收到客户十多万好评，感谢大家的支持！',
      time: '15:36',
      avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=user2',
      sender: '店铺客服'
    }
  ]
};

// ==================== DOM元素 ====================
const chatList = document.getElementById('chatList');
const chatEmpty = document.getElementById('chatEmpty');
const chatWindow = document.getElementById('chatWindow');
const chatMessages = document.getElementById('chatMessages');
const chatHeaderAvatar = document.getElementById('chatHeaderAvatar');
const chatHeaderName = document.getElementById('chatHeaderName');
const chatHeaderStatus = document.getElementById('chatHeaderStatus');
const messageInput = document.getElementById('messageInput');
const sendBtn = document.getElementById('sendBtn');
const searchInput = document.getElementById('searchInput');

// ==================== 全局变量 ====================
let currentChatId = null;
let allChats = [...mockChats];
let filteredChats = [...mockChats];

// ==================== 渲染聊天列表 ====================
function renderChatList() {
  if (filteredChats.length === 0) {
    chatList.innerHTML = '<div class="empty-state"><div class="empty-text">暂无会话</div></div>';
    return;
  }

  chatList.innerHTML = filteredChats.map(chat => `
    <div class="chat-item ${chat.id === currentChatId ? 'active' : ''} ${chat.unread > 0 ? 'unread' : ''} ${chat.pinned ? 'pinned' : ''}" 
         data-id="${chat.id}">
      <div class="chat-avatar">
        <img src="${chat.avatar}" alt="${chat.name}">
        <span class="status-dot ${chat.online ? 'online' : 'offline'}"></span>
      </div>
      <div class="chat-info">
        <div class="chat-info-top">
          <span class="chat-name" ${chat.id === SYSTEM_NOTIFICATION_ID ? 'style="font-size: 94%;"' : ''}>${chat.name}</span>
          <span class="chat-time">${chat.time}</span>
        </div>
        <div class="chat-preview" ${chat.id === SYSTEM_NOTIFICATION_ID ? 'style="font-size: 80%; color: #818181;"' : ''}>
          <span class="chat-message">${chat.lastMessage}</span>
          ${chat.unread > 0 ? `<span class="chat-badge">${chat.unread}</span>` : ''}
        </div>
      </div>
    </div>
  `).join('');

  // 绑定点击事件
  document.querySelectorAll('.chat-item').forEach(item => {
    item.addEventListener('click', () => {
      const chatId = item.dataset.id === SYSTEM_NOTIFICATION_ID ? SYSTEM_NOTIFICATION_ID : parseInt(item.dataset.id);
      openChat(chatId);
    });
  });
}

// ==================== 打开聊天 ====================
async function openChat(chatId) {
  currentChatId = chatId;
  const chat = allChats.find(c => c.id === chatId);
  
  if (!chat) return;

  // 清除未读标记
  chat.unread = 0;

  // 隐藏空状态，显示聊天窗口
  chatEmpty.style.display = 'none';
  chatWindow.style.display = 'flex';

  // 更新头部信息
  chatHeaderAvatar.src = chat.avatar;
  chatHeaderName.textContent = chat.name;
  chatHeaderStatus.textContent = chat.online ? '在线' : '离线';

  // 🔔 如果是系统通知，加载真实的通知数据
  if (chatId === SYSTEM_NOTIFICATION_ID) {
    await loadNotificationMessages();
  } else {
    // 渲染消息
    renderMessages(chatId);
  }

  // 更新列表
  renderChatList();
}

// ==================== 加载通知消息 ====================
async function loadNotificationMessages() {
  try {
    // 从主进程获取通知列表
    const notifications = await ipcRenderer.invoke('get-notifications');
    
    if (!notifications || notifications.length === 0) {
      chatMessages.innerHTML = `
        <div class="empty-state">
          <div class="empty-icon" style="margin-top: 72px;">
            <svg height="134" viewBox="0 0 154 134" width="154" xmlns="http://www.w3.org/2000/svg" style="width: 228px; height: auto;">
              <g><path d="M 109.97 114.31 L 132.88 132.31 L 132.88 37.14 C 132.88 35.78 132.34 34.47 131.38 33.51 C 130.41 32.54 129.10 32.00 127.74 32.00 L 35.14 32.00 C 32.30 32.00 30.00 34.30 30.00 37.14 L 30.00 109.16 C 30.00 112.00 32.30 114.31 35.14 114.31 L 109.97 114.31 Z" fill="#e2e5f1" fill-opacity="0.8"/></g>
              <g><path d="M 55.99 99.81 L 60.19 97.38 L 62.62 101.58 L 20.61 125.83 L 18.19 121.63 L 22.39 119.21 L 13.90 104.51 C 8.54 95.23 11.72 83.36 21.00 78.01 C 30.28 72.65 42.14 75.83 47.50 85.11 L 55.99 99.81 Z M 37.74 121.55 L 50.34 114.27 L 52.77 118.47 L 40.16 125.75 Z" fill="#417aff" fill-opacity="0.8"/></g>
              <g><path d="M 148.38 103.74 C 145.38 103.74 142.95 101.30 142.95 98.30 C 142.95 95.30 145.38 92.87 148.38 92.87 C 151.39 92.87 153.82 95.30 153.82 98.30 C 153.80 101.30 151.38 103.72 148.38 103.74 Z M 148.38 94.73 C 146.41 94.73 144.81 96.33 144.81 98.30 C 144.81 100.27 146.41 101.87 148.38 101.87 C 150.35 101.87 151.95 100.27 151.95 98.30 C 151.94 96.34 150.35 94.75 148.38 94.73 Z" fill="#a4bfff" fill-opacity="0.8"/></g>
              <g><path d="M 61.01 15.56 L 77.92 42.14 C 78.13 42.47 78.48 42.68 78.87 42.72 C 79.09 42.75 79.31 42.71 79.52 42.63 C 79.67 42.56 79.81 42.47 79.92 42.35 L 86.30 35.91 C 86.65 35.56 87.19 35.48 87.63 35.71 L 93.73 38.91 C 94.07 39.10 94.48 39.11 94.83 38.95 C 94.97 38.89 95.10 38.80 95.21 38.70 C 95.60 38.32 95.73 37.75 95.52 37.24 L 93.08 31.49 C 92.87 31.01 92.51 30.61 92.05 30.37 L 68.30 17.85 L 95.19 26.52 C 95.39 26.59 95.62 26.53 95.77 26.38 L 101.60 20.49 C 101.98 20.16 102.11 19.62 101.91 19.15 C 101.77 18.67 101.34 18.33 100.84 18.30 L 62.26 13.58 C 62.03 13.54 61.80 13.57 61.59 13.66 C 61.35 13.76 61.14 13.94 61.01 14.16 C 60.72 14.58 60.72 15.14 61.01 15.56 Z" fill="#697391" fill-opacity="0.8"/></g>
              <g><path d="M 101.94 37.54 C 101.94 37.54 130.74 50.83 128.11 58.68 C 125.48 66.53 116.25 59.65 120.79 55.07 C 125.32 50.49 137.86 54.83 137.82 70.78 C 137.78 86.74 128.75 108.28 87.83 119.46" fill="none" stroke="#c2c8d8" stroke-dasharray="2 2" stroke-opacity="0.8" stroke-width="1"/></g>
              <g><path d="M 30.10 59.46 L 21.83 51.19 L 30.10 42.92 L 38.36 51.19 Z M 24.72 51.19 L 30.18 56.65 L 35.63 51.19 L 30.18 45.73 Z" fill="#c2c8d8" fill-opacity="0.8"/></g>
              <g><path d="M 114.48 17.05 C 113.93 17.05 113.48 16.60 113.48 16.05 L 113.48 13.82 L 111.26 13.82 C 110.70 13.82 110.26 13.37 110.26 12.82 L 110.26 12.67 C 110.26 12.12 110.70 11.67 111.26 11.67 L 113.48 11.67 L 113.48 9.45 C 113.48 8.89 113.93 8.45 114.48 8.45 L 114.63 8.45 C 115.18 8.45 115.63 8.89 115.63 9.45 L 115.63 11.67 L 117.86 11.67 C 118.41 11.67 118.86 12.12 118.86 12.67 L 118.86 12.82 C 118.86 13.37 118.41 13.82 117.86 13.82 L 115.63 13.82 L 115.63 16.05 C 115.63 16.60 115.18 17.05 114.63 17.05 Z" fill="#417aff" fill-opacity="0.8"/></g>
              <g><path d="M 66.93 134.23 C 66.37 134.23 65.93 133.79 65.93 133.23 L 65.93 129.62 L 62.31 129.62 C 61.75 129.62 61.31 129.17 61.31 128.62 L 61.31 127.53 C 61.31 126.98 61.75 126.53 62.31 126.53 L 65.93 126.53 L 65.93 122.92 C 65.93 122.36 66.37 121.92 66.93 121.92 L 68.01 121.92 C 68.56 121.92 69.01 122.36 69.01 122.92 L 69.01 126.53 L 72.63 126.53 C 73.18 126.53 73.63 126.98 73.63 127.53 L 73.63 128.62 C 73.63 129.17 73.18 129.62 72.63 129.62 L 69.01 129.62 L 69.01 133.24 C 69.01 133.79 68.56 134.24 68.01 134.24 Z" fill="#c2c8d8" fill-opacity="0.8"/></g>
              <g><path d="M 15.61 30.73 C 15.06 30.73 14.61 30.28 14.61 29.73 L 14.61 27.17 L 12.06 27.17 C 11.50 27.17 11.06 26.72 11.06 26.17 L 11.06 25.80 C 11.06 25.25 11.50 24.80 12.06 24.80 L 14.61 24.80 L 14.61 22.25 C 14.61 21.69 15.06 21.25 15.61 21.25 L 15.98 21.25 C 16.54 21.25 16.98 21.69 16.98 22.25 L 16.98 24.80 L 19.54 24.80 C 20.09 24.80 20.54 25.25 20.54 25.80 L 20.54 26.17 C 20.54 26.72 20.09 27.17 19.54 27.17 L 16.98 27.17 L 16.98 29.73 C 16.98 30.28 16.54 30.73 15.98 30.73 Z" fill="#f1f3f8" fill-opacity="0.8"/></g>
              <path d="M 89.47 77.48 L 97.96 69.00 L 102.20 73.24 L 93.71 81.73 Z M 61.00 72.74 L 65.24 68.50 L 73.72 76.98 L 69.48 81.23 Z M 78.60 75.00 L 78.60 63.00 L 84.60 63.00 L 84.60 75.00 Z" fill="#ffffff" fill-opacity="0.8"/>
            </svg>
          </div>
          <div class="empty-text" style="font-size: 17px; margin-top: 58px;">暂无通知消息</div>
        </div>
      `;
      return;
    }

    // 转换通知为消息格式并渲染
    chatMessages.innerHTML = notifications.map(notif => {
      const priorityConfig = {
        urgent: { text: '紧急', color: '#ff4d4f' },
        high: { text: '高', color: '#faad14' },
        normal: { text: '普通', color: '#40a9ff' },
        low: { text: '低', color: '#8c8c8c' }
      };
      
      const priority = priorityConfig[notif.priority] || priorityConfig.normal;

      // 格式化时间
      const notifDate = new Date(notif.createdAt);
      const timeStr = notifDate.toLocaleString('zh-CN', { 
        month: '2-digit', 
        day: '2-digit', 
        hour: '2-digit', 
        minute: '2-digit' 
      });

      return `
        <div class="message-item notification-message ${notif.isRead ? 'read' : 'unread'}" data-notif-id="${notif.id}">
          <img class="message-avatar" src="../assets/cd01.svg" alt="系统通知">
          <div class="message-content">
            <div class="message-info">
              <div class="notification-title-row">
                <span class="notification-title-main">${notif.title}</span>
                <span class="notification-priority-badge" style="background-color: ${priority.color};">${priority.text}</span>
              </div>
              <span class="message-time">${timeStr}</span>
            </div>
            <div class="message-bubble notification-bubble">
              <div class="notification-content">${notif.content}</div>
              ${notif.imageUrl ? `<img class="notification-image" src="${notif.imageUrl}" alt="通知图片">` : ''}
              <div class="notification-actions">
                ${!notif.isRead ? 
                  `<button class="notif-action-btn mark-read" data-notif-id="${notif.id}">标为已读</button>` : 
                  `<span class="read-status">✓ 已读</span>`
                }
              </div>
            </div>
          </div>
        </div>
      `;
    }).join('');

    // 绑定标记已读按钮
    document.querySelectorAll('.mark-read').forEach(btn => {
      btn.addEventListener('click', async (e) => {
        e.stopPropagation();
        const notifId = parseInt(btn.dataset.notifId);
        await markNotificationAsRead(notifId);
      });
    });

    // 滚动到底部
    chatMessages.scrollTop = chatMessages.scrollHeight;

    // 更新未读数量
    await updateNotificationBadge();
  } catch (error) {
    console.error('加载通知消息失败:', error);
    chatMessages.innerHTML = `
      <div class="empty-state">
        <div class="empty-icon">⚠️</div>
        <div class="empty-text">加载通知失败</div>
      </div>
    `;
  }
}

// ==================== 标记通知为已读 ====================
async function markNotificationAsRead(notificationId) {
  try {
    await ipcRenderer.invoke('mark-notification-read', notificationId, true);
    console.log('已标记通知为已读:', notificationId);
    
    // 重新加载通知消息
    await loadNotificationMessages();
  } catch (error) {
    console.error('标记通知失败:', error);
  }
}

// ==================== 更新通知徽章 ====================
async function updateNotificationBadge() {
  try {
    const unreadCount = await ipcRenderer.invoke('get-unread-count');
    const notificationChat = allChats.find(c => c.id === SYSTEM_NOTIFICATION_ID);
    
    if (notificationChat) {
      notificationChat.unread = unreadCount;
      
      if (unreadCount > 0) {
        notificationChat.lastMessage = `您有 ${unreadCount} 条未读通知`;
        notificationChat.time = '刚刚';
      } else {
        notificationChat.lastMessage = '暂无未读通知';
      }
      
      // 重新渲染聊天列表
      renderChatList();
    }
  } catch (error) {
    console.error('更新通知徽章失败:', error);
  }
}

// ==================== 渲染消息 ====================
function renderMessages(chatId) {
  const messages = mockMessages[chatId] || [];
  
  if (messages.length === 0) {
    chatMessages.innerHTML = '<div class="empty-state"><div class="empty-text">暂无消息</div></div>';
    return;
  }

  chatMessages.innerHTML = messages.map(msg => {
    const isMine = msg.type === 'sent';
    return `
      <div class="message-item ${isMine ? 'mine' : ''}">
        <img class="message-avatar" src="${isMine ? 'https://api.dicebear.com/7.x/avataaars/svg?seed=me' : msg.avatar}" alt="头像">
        <div class="message-content">
          <div class="message-info">
            ${!isMine ? `<span class="message-sender">${msg.sender}</span>` : ''}
            <span class="message-time">${msg.time}</span>
          </div>
          <div class="message-bubble">${msg.content}</div>
        </div>
      </div>
    `;
  }).join('');

  // 滚动到底部
  chatMessages.scrollTop = chatMessages.scrollHeight;
}

// ==================== 发送消息 ====================
function sendMessage() {
  const content = messageInput.value.trim();
  
  if (!content || !currentChatId) return;

  // 创建消息
  const message = {
    id: Date.now(),
    type: 'sent',
    content: content,
    time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=me'
  };

  // 添加到消息列表
  if (!mockMessages[currentChatId]) {
    mockMessages[currentChatId] = [];
  }
  mockMessages[currentChatId].push(message);

  // 更新聊天列表中的最后一条消息
  const chat = allChats.find(c => c.id === currentChatId);
  if (chat) {
    chat.lastMessage = content;
    chat.time = message.time;
  }

  // 清空输入框
  messageInput.value = '';

  // 重新渲染
  renderMessages(currentChatId);
  renderChatList();
}

// ==================== 搜索功能 ====================
function searchChats(keyword) {
  keyword = keyword.trim().toLowerCase();
  
  if (!keyword) {
    filteredChats = [...allChats];
  } else {
    filteredChats = allChats.filter(chat => 
      chat.name.toLowerCase().includes(keyword) || 
      chat.lastMessage.toLowerCase().includes(keyword)
    );
  }
  
  renderChatList();
}

// ==================== 事件绑定 ====================
sendBtn.addEventListener('click', sendMessage);

messageInput.addEventListener('keypress', (e) => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
    sendMessage();
  }
});

searchInput.addEventListener('input', (e) => {
  searchChats(e.target.value);
});

// ==================== 初始化 ====================
async function initialize() {
  console.log('聊天列表页面初始化...');
  
  // 渲染聊天列表
  renderChatList();
  
  // 更新通知徽章
  await updateNotificationBadge();
  
  // 监听新通知事件
  ipcRenderer.on('notification-received', async (event, notification) => {
    console.log('收到新通知:', notification);
    
    // 更新通知徽章
    await updateNotificationBadge();
    
    // 如果当前正在查看系统通知，刷新消息列表
    if (currentChatId === SYSTEM_NOTIFICATION_ID) {
      await loadNotificationMessages();
    }
  });
  
  // 监听通知已读事件
  ipcRenderer.on('notification-read', async (event, notification) => {
    console.log('通知已读:', notification);
    
    // 更新通知徽章
    await updateNotificationBadge();
    
    // 如果当前正在查看系统通知，刷新消息列表
    if (currentChatId === SYSTEM_NOTIFICATION_ID) {
      await loadNotificationMessages();
    }
  });
  
  console.log('聊天列表页面初始化完成');
}

// 页面加载时初始化
window.addEventListener('DOMContentLoaded', initialize);
